<?php

namespace app\common\traits;

use FFMpeg\FFProbe;
use think\Log;

trait SourceDurationPart
{
    public function getSourceDuration($attribute, bool $isEncrypt = false)
    {
        $duration = 0;
        $path = $this[$attribute] ?? '';
        if ($path) {
            if ($isEncrypt) {
                $path = decrypt($path);
            }
            $fullPath = public_path($path);
            if (file_exists($fullPath)) {
                try {
                    $config = [];
                    if (config('app_debug')) {
                        $config['ffprobe.binaries'] = config('ffmpeg.ffprobe_path');
                    }
                    $duration = FFProbe::create($config)->format($fullPath)->get('duration');
                } catch (\Throwable $exception) {
                    Log::error(sprintf(
                        'ffmpeg调用失败:%s',
                        $exception->getMessage(),
                    ));
                }
            }
        }
        return $duration;
    }
}